"use client";
import {
  PageContainer,
  ProForm,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
} from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { Button, Card, Col, Form, message, Row, Space } from "antd";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { RollbackOutlined } from "@ant-design/icons";
import {
  addNoticeApi,
  updateNoticeApi,
  getNoticeApi,
} from "@/lib/api/system/notice";
import { Notice } from "@/lib/api/system/notice.d";
import { getDictDatasByTypesApi } from "@/lib/api/system/dict";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { useState } from "react";

export default function Page() {
  const { type } = useParams();
  const router = useRouter();
  const params = useSearchParams();
  const noticeId = params.get("noticeId");
  const [noticeContent, setNoticeContent] = useState("请输入内容");

  const title = type === "add" ? "新增公告" : "修改公告";

  const { data: dictData } = useRequest(() =>
    getDictDatasByTypesApi(["sys_notice_status", "sys_notice_type"]),
  );

  const [status, typeDict] = dictData ?? [[], []];

  const { run: addNotice, loading: addNoticeLoading } = useRequest(
    addNoticeApi,
    {
      manual: true,
      onSuccess: () => {
        message.success("新增成功");
        router.back();
      },
      onError: (error: any) => {
        message.error(error.msg);
      },
    },
  );

  const { run: updateNotice, loading: updateNoticeLoading } = useRequest(
    (params) => updateNoticeApi({ ...params, noticeId: noticeId }),
    {
      manual: true,
      onSuccess: () => {
        message.success("修改成功");
        router.back();
      },
      onError: (error: any) => {
        message.error(error.msg);
      },
    },
  );

  const extraProps =
    type !== "add"
      ? {
          request: async () => {
            const res = await getNoticeApi(noticeId as string);
            setNoticeContent(res.data.noticeContent);
            return res.data;
          },
        }
      : {
          defaultFormValues: {
            noticeStatus: "1",
          },
        };

  return (
    <PageContainer
      title={title}
      extra={
        <Button icon={<RollbackOutlined />} onClick={() => router.back()}>
          返回
        </Button>
      }
    >
      <Card>
        <ProForm
          layout="horizontal"
          submitter={{
            render: (_, dom) => {
              return (
                <Row>
                  <Col span={14} offset={4}>
                    <Space>{dom}</Space>
                  </Col>
                </Row>
              );
            },
            searchConfig: { submitText: "保存" },
          }}
          className="max-w-[800px] mx-auto my-10"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          loading={addNoticeLoading || updateNoticeLoading}
          onFinish={async (values: Notice) => {
            if (type === "add") {
              await addNotice(values);
            } else {
              await updateNotice(values);
            }
          }}
          {...extraProps}
        >
          <ProFormText
            name="noticeTitle"
            label="通知标题"
            required
            rules={[{ required: true, message: "请输入通知标题" }]}
          />
          <ProFormSelect
            name="noticeType"
            label="通知类型"
            options={typeDict.map((item) => ({
              label: item.dictLabel,
              value: item.dictValue,
            }))}
            rules={[{ required: true, message: "请选择通知类型" }]}
          />
          <ProFormRadio.Group
            name="status"
            label="状态"
            options={status.map((item) => ({
              label: item.dictLabel,
              value: item.dictValue,
            }))}
          />
          <Form.Item className="mb-16" label="通知内容" name="noticeContent">
            <ReactQuill
              id="noticeContent"
              className="h-[300px]"
              theme="snow"
              value={noticeContent}
              onChange={setNoticeContent}
            />
          </Form.Item>
        </ProForm>
      </Card>
    </PageContainer>
  );
}
